package com.adopapa.nezhacloud.ddd.conf;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;

public class MyClientHttpRequestFactory extends SimpleClientHttpRequestFactory {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Override
	protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
		if (!(connection instanceof HttpsURLConnection)) {
			super.prepareConnection(connection, httpMethod);
			return;
		}

		try {
			HttpsURLConnection httpsURLConnection = (HttpsURLConnection) connection;

			TrustManager[] trustManagers = new TrustManager[] { new MyX509TrustManager() };

			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
			sslContext.init(null, trustManagers, new java.security.SecureRandom());
			// 从上述SSLContext对象中得到SSLSocketFactory对象
			SSLSocketFactory ssf = sslContext.getSocketFactory();
			httpsURLConnection.setSSLSocketFactory(ssf);

			super.prepareConnection(httpsURLConnection, httpMethod);

		} catch (Exception e) {
			logger.error(ExceptionUtils.getStackTrace(e));
		}
		
	}
	
	

	static class MyX509TrustManager implements X509TrustManager {
		
		public void checkClientTrusted(X509Certificate[] chain, String authType) //
				throws CertificateException {
		}

		public void checkServerTrusted(X509Certificate[] chain, String authType) //
				throws CertificateException {
		}

		public X509Certificate[] getAcceptedIssuers() {
			return null;
		}
	}
}
